package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*****
 * 项目拦截器
 */

@Slf4j
@Component
public class ProjectInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       /* //1.获取请求路径
        String requestURL = request.getRequestURL().toString();

        //2.设置哪些请求进行放行
        String[] urls = new String[]{"/login", "/logout", "/backend", "/front"};
        //3.判断本次请求中是否包含上述信息
        for (int i = 0; i < urls.length; i++) {
            if (requestURL.contains(urls[i])) {
                return true;//放行
            }
        }*/
        // 员工登录判断
        if (request.getSession().getAttribute("emp") != null) {
            //5.登录成功
            Long empId = (Long) request.getSession().getAttribute("emp");
            BaseContext.setCurrentId(empId);
            log.info("员工登录成功,用户名:" + empId);
            return true;
        }

        //用户登录判断
        if (request.getSession().getAttribute("user") != null) {
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(1541404709952548866L);
            log.info("用户登录成功,用户id: {}", userId);
            return true;
        }

        //没有登录
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
